package com.gogo.mall.jwt;

import com.auth0.jwt.JWT;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.gogo.mall.entity.QyMember;
import com.gogo.mall.service.QyMemberService;
import com.gogo.mall.utils.JwtUtil;

import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

public class AuthenticationInterceptor implements HandlerInterceptor {

    @Autowired
    private QyMemberService userLoginService;
    /*
    controller执行之前
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object object){
        // 从http请求头中取出token
        String token = request.getHeader("token");
        // 如果不是映射到方法直接通过
        if(!(object instanceof HandlerMethod)){
            return true;
        }
        HandlerMethod handlerMethod = (HandlerMethod) object;
        Method method = handlerMethod.getMethod();
        // 方法是否带有UserLoginToken注释
        if(method.isAnnotationPresent(UserLoginToken.class)){
            UserLoginToken userLoginToken = method.getAnnotation(UserLoginToken.class);
            if(userLoginToken.required()){
                return true;
            }
        }

        // 方法是否带有PassToken注释
        if(method.isAnnotationPresent(PassToken.class)){
            PassToken passToken = method.getDeclaredAnnotation(PassToken.class);
            if(passToken.required()){
                // 执行认证
                if(token == null){
                    throw new RuntimeException("无token，请重新登录！");
                }
                // 获取token中的userId
                long userId;
                try {
                    userId = JWT.decode(token).getClaim("id").asLong();
                } catch (JWTDecodeException j){
                    throw new RuntimeException("访问异常！");
                }
                QyMember user = userLoginService.queryById((int) userId);

                if(ObjectUtils.isEmpty(user)){
                    throw new RuntimeException("当前用户不存在，请重新登录！");
                }

                try {
                    Claims claims = JwtUtil.parseJWT(token, user);
                    boolean tokenExpired = JwtUtil.isTokenExpired(claims);
                }catch (RuntimeException e){
                    throw new RuntimeException("token已过期，请重新登录");
                }

                Boolean verify = JwtUtil.isVerify(token, user);
                if(!verify){
                    throw new RuntimeException("非法访问！");
                }
//                System.out.println(user.toString());
                request.setAttribute("UserInfo",user);
                return true;
            }
        }
        return true;
    }
    /*
    controller执行后，页面渲染前
     */
    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }
    /*
    页面渲染后
     */
    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }
}

